﻿/**
 * Created by zjy on 2016/1/16.
 */
var http=require('http');
//var request=require('request');
var fs=require('fs');
var querystring=require('querystring');
var urls=require('url');
var iconvLite = require('iconv-lite');
var cheerio = require('cheerio');
var zlib = require('zlib');
var Gwxk = {
    //登录
    login: function ($data,$callback) {
        var self = this;
        var $files={
            "USERNAME":$data.username,
            "PASSWORD":$data.password
        };
        var result={
            status:null,
            data:null,
            info:null
        };
        console.log($files);
        var $url=this.getUrl('login');
        this.sendPost($url, null, $files, function (res,data) {
            console.log(res.statusCode);
            if(res.statusCode==302){
                const cookie=res.headers['set-cookie'].join("; ");
                self.sendGet(res.headers['location'],cookie, function (res, data) {
                    //console.log(data);
                    var $pattern=/<div id="Top1_divLoginName" class="Nsb_top_menu_nc" style=".+?">(.+?)\([0-9]+?\)<\/div>/;
                    var match=$pattern.exec(data);
                    if(match){
                        result.status=true;
                        result.info='login success';
                        result.data={
                            username:$data.username,
                            name:match[1],
                            cookie: cookie
                        }
                    }
                    else{
                        result.status=false;
                        result.info='login error';
                    }
                    $callback(result);
                });
            }
            else{
                result.status=false;
                result.info='login error';
                $callback(result);
            }
        });
    },
    //获取成绩信息
    getScore: function ($cookie, $filed,$callback) {
        var self=this;
        var $url=self.getUrl('score');
        var field={
            "kksj":$filed.xq,
            "kcxz":$filed.kcxz || '',
            "kcmc":$filed.kcmc || '',
            "fxkc":$filed.fxkc || 0,
            "xsfs":$filed.xsfs || 'all'
        };

        var result={
            status:null,
            data:null,
            info:null
        };

        self.sendPost($url,$cookie, field, function (res, data) {

            if(res.statusCode == 200 ){
                result.status = true;
                var $ = cheerio.load(data);
                var dataArr = [];
                $("#dataList tr").each(function (i, v) {
                    if(i==0) return true;
                    var score = {};
                    $(v).find('td').each(function(j ,d){
                        switch (j){
                            case 0:
                                score['order'] = $(d).text();
                                break;
                            case 1:
                                score['xq'] = $(d).text();
                                break;
                            case 2:
                                score['coder'] = $(d).text();
                                break;
                            case 3:
                                score['name'] = $(d).text();
                                break;
                            case 4:
                                score['score'] = $(d).text();
                                break;
                            case 5:
                                score['credit'] = $(d).text();
                                break;
                            case 6:
                                score['period'] = $(d).text();
                                break;
                            case 7:
                                score['way'] = $(d).text();
                                break;
                            case 8:
                                score['prop'] = $(d).text();
                                break;
                            case 9:
                                score['nature'] = $(d).text();
                                break;
                            case 10:
                                score['type'] = $(d).text();
                                break;
                        }
                    });
                    dataArr.push(score);
                });

                result.data = dataArr;
            }
            else{
                result.status = false;
                result.info = "get course error";
            }
            $callback(result);
        })
    },
    //获取成绩选项
    getScoreOption: function ($cookie , $callback) {
        var self = this;
        var $url=this.getUrl('scoreOption');
        self.sendGet($url,$cookie, function (res, data) {
            var result={
                status:null,
                data:null,
                info:null
            };

            if(res.statusCode == 200 ){
                result.status = true;
                var $ = cheerio.load(data);
                var optionData = {};
                var optionArr = [];
                $("#kksj option").each(function (i, v) {
                    optionArr.push({text:$(v).text(),value:$(v).val()})
                });
                optionData['options'] = optionArr;
                result.data = optionData;
            }
            else{
                result.status = false;
                result.info = "get score option error";
            }
            $callback(result);
        })
    },
    //获取课程信息
    getCourse: function($cookie, $data, $callback) {
        var self = this;
        var $url=this.getUrl('course');
        if(typeof $data == 'function'){
            $callback = $data;
            self.sendGet($url,$cookie, function (res, data) {
                self.dealCourse(res, data, $callback);
            })
        }
        else{
            if($data){
                var $files={
                    "xnxq01id":$data.xq,
                    "sfFD":1
                };
                self.sendPost($url,$cookie, $files, function (res, data) {
                    self.dealCourse(res, data, $callback);
                })
            }
            else{
                self.sendGet($url,$cookie, function (res, data) {
                    self.dealCourse(res, data, $callback);
                })
            }
        }
    },
    //获取课程选项
    getCourseOption: function ($cookie , $callback) {
        var self = this;
        var $url=this.getUrl('course');
        self.sendGet($url,$cookie, function (res, data) {
            var result={
                status:null,
                data:null,
                info:null
            };

            if(res.statusCode == 200 ){
                result.status = true;
                var $ = cheerio.load(data);
                var optionData = {};
                var optionArr = [];
                $("#xnxq01id option").each(function (i, v) {
                    optionArr.push({text:$(v).text(),value:$(v).val()})
                });
                optionData['selected']=$("#xnxq01id option[selected]").val();
                optionData['options'] = optionArr;
                result.data = optionData;
            }
            else{
                result.status = false;
                result.info = "get course option error";
            }
            $callback(result);
        })
    },
    //处理课程信息
    dealCourse: function (res, html,$callback) {
        var result={
            status:null,
            data:null,
            info:null
        };

        if(res.statusCode == 200 ){
            var $ = cheerio.load(html);
            var dataArr = [];
            $("#kbtable tr").each(function (i, v) {
                var courseArr = [];
                $(v).find('.kbcontent').each(function(j ,d){
                    courseArr.push($(d).text())
                });
                if(courseArr.length>0){
                    dataArr.push(courseArr);
                }
            });
            if(dataArr.length == 0){
                result.status = false;
                result.info="教务系统爬取不到相应信息";
            }
            else{
                result.status = true;
                result.data = dataArr;
            }
        }
        else{
            result.status = false;
            result.info = "get course error";
        }
        $callback(result);
    },
    //等级考试
    getCet: function ($cookie, $callback) {
        var self=this;
        var $url=self.getUrl('cet');

        var result={
            status:null,
            data:null,
            info:null
        };

        self.sendGet($url, $cookie, function (res, data) {
            if(res.statusCode == 200 ){
                result.status = true;
                var $ = cheerio.load(data);
                var dataArr = [];
                $("#dataList tr").each(function (i, v) {
                    if(i==0 || i==1 ) return true;
                    var cet = {};
                    $(v).find('td').each(function(j ,d){
                        switch (j){
                            case 0:
                                cet['order'] = $(d).text();
                                break;
                            case 1:
                                cet['name'] = $(d).text();
                                break;
                            case 4:
                                cet['score'] = $(d).text();
                                break;
                            case 8:
                                cet['time'] = $(d).text();
                                break;
                        }
                    });
                    dataArr.push(cet);
                });
                result.data = dataArr;
            }
            else{
                result.status = false;
                result.info = "get course error";
            }
            $callback(result);
        });
    },
    //post
    sendPost: function ($url, $cookie ,$filed , $callback) {
        var self=this;
        var $param=querystring.stringify($filed),
            url=urls.parse($url),
            $origin='http://'+url.host,
            $header={
                'Proxy-Connection': 'keep-alive',
                'Content-Length':$param.length,
                'Cache-Control': 'max-age=0',
                'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Origin': $origin,
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.12 Safari/537.31',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept-Encoding': 'gzip,deflate,sdch',
                'Accept-Language': 'zh-CN,zh;q=0.8',
                'Accept-Charset': 'GBK,utf-8;q=0.7,*;q=0.3'
            };
        if($cookie){
            $header.Cookie=$cookie;
        }
        var $options={
            host:url.host,
            path:url.path,
            method:"POST",
            headers:$header
        };

        var req=http.request($options, function (res) {
            var buffers = [],encoding = res.headers['content-encoding'];
            res.on('data', function (chunk) {
                buffers.push(chunk);
            });
            res.on("end",function(){
                var buffer = Buffer.concat(buffers);
                if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function (err, decoded) {
                        var data = iconvLite.decode(decoded, 'utf-8');
                        $callback(res,data);
                    });
                } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function (err, decoded) {
                        var data = iconvLite.decode(decoded, 'utf-8');
                        $callback(res,data);
                    });
                } else {
                    var data = iconvLite.decode(buffer, 'utf-8');
                    $callback(res,data);
                }
            });
        });
        req.end($param);
    },
    //get
    sendGet: function ($url, $cookie, $filed , $callback) {
        var self=this;
        if($filed){
            if(typeof $filed == 'function'){
                $callback=$filed;
            }
            else
                $url+="?"+querystring.stringify($filed);
        }
        var url=urls.parse($url);
        if($cookie){
            var $header = {
                'Cookie':$cookie
            };
        }
        var options={
            host:url.host,
            path:url.path,
            method:'GET',
            headers:$header
        };
        var req=http.request(options,function(res){
            var buffers = [],encoding = res.headers['content-encoding'];
            res.on('data', function (chunk) {
                buffers.push(chunk);
            });
            res.on("end",function(){
                var buffer = Buffer.concat(buffers);
                if (encoding == 'gzip') {
                    zlib.gunzip(buffer, function (err, decoded) {
                        var data = iconvLite.decode(decoded, 'utf-8');
                        $callback(res,data);
                    });
                } else if (encoding == 'deflate') {
                    zlib.inflate(buffer, function (err, decoded) {
                        var data = iconvLite.decode(decoded, 'utf-8');
                        $callback(res,data);
                    });
                } else {
                    var data = iconvLite.decode(buffer, 'utf-8');
                    $callback(res,data);
                }
            });
        });
        req.end();
    },
    //获取url
    getUrl:function(type){
        var url=null;
        switch (type){
            case 'login'://登陆的url
                url='http://jxgl.gdufs.edu.cn/jsxsd/xk/LoginToXkLdap';
                break;
            case 'score'://成绩的列表
                url='http://jxgl.gdufs.edu.cn/jsxsd/kscj/cjcx_list';
                break;
            case 'scoreOption':
                url = "http://jxgl.gdufs.edu.cn/jsxsd/kscj/cjcx_query";
                break;
            case 'cet'://等级考试
                url = 'http://jxgl.gdufs.edu.cn/jsxsd/kscj/djkscj_list';
                break;
            case 'course':
                url = 'http://jxgl.gdufs.edu.cn/jsxsd/xskb/xskb_list.do';
                break;
            case 'index'://首页
                url='http://jxgl.gdufs.edu.cn/jsxsd/framework/main.jsp';
                break;
        }
        return url;
    }
};
module.exports=Gwxk;